package cn.huiyunche.base.service.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * The type Validation params.
 *
 * @ClassName: ValidationParams
 * @Description: 注解方式的参数验证
 * @author: Aaron
 * @date: 2016年10月12日 下午1:52:04
 */
public class ValidationParams {

    /**
     * Validation.记录日志，抛入异常
     *
     * @param LOGGER     the logger
     * @param methodName the method name
     * @param object     the object
     * @param groups     the groups
     */
    public static void validation(final Logger LOGGER, String methodName, Object object, Class<?>... groups) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> set;
        if (null == groups) {
            set = validator.validate(object);
        } else {
            set = validator.validate(object, groups);
        }
        if (CollectionUtils.isNotEmpty(set)) {
            LOGGER.error("{} {}", methodName, set.iterator().next().getMessage());
            throw new IllegalArgumentException(set.iterator().next().getMessage());
        }
    }

    /**
     * Validation set.返回错误信息
     *
     * @param object the object
     * @return the set
     */
    public static Set<ConstraintViolation<Object>> validation(Object object) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> set = validator.validate(object);
        if (CollectionUtils.isNotEmpty(set)) {
            return set;
        }
        return null;
    }
}
